package com.zam.web.courseController;

import cn.hutool.core.collection.ListUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery;
import com.zam.comment.Result;
import com.zam.pojo.Course;
import com.zam.pojo.CourseUser;
import com.zam.service.ICourseService;
import com.zam.service.ICourseUserService;
import org.apache.hadoop.fs.FileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/******************************
 controller层
 ******************************/
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private ICourseService courseService;

    // 配置连接
    FileSystem fs = null;

    @Autowired
    private ICourseUserService courseUserService;

    /*
    添加数据
    */
    @PostMapping
    public boolean save(@RequestBody Course course) {
        return courseService.saveOrUpdate(course);
    }

    /*
    删除数据
    */
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return courseService.removeById(id);
    }

    /*
    删除多个数据
    */
    @DeleteMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return courseService.removeByIds(ids);
    }

    /*
     查看全部
    */
    @GetMapping
    public List<Course> findAll() {
        return courseService.list();
    }

    /*
    根据id查看
    */
    @GetMapping("/{id}")
    public Course findOne(@PathVariable Integer id) {
        return courseService.getById(id);
    }

    /*
    分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, Course course) {
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        if (course.getFileName() != null && !course.getFileName().isEmpty()) {
            queryWrapper.like(Course::getFileName, course.getFileName());
        }
        if (course.getFileType() != null && !course.getFileType().isEmpty()) {
            queryWrapper.like(Course::getFileType, course.getFileType());
        }
        if (course.getFileUserId() != null && !course.getFileUserId().isEmpty()) {
            queryWrapper.eq(Course::getFileUserId, course.getFileUserId());
        }
        if (course.getCollectCount() != null && !course.getCollectCount().isEmpty()) {
            queryWrapper.orderBy(true, false,Course::getCollectCount);
        }
        queryWrapper.eq(Course::getIsShare, "1");
        queryWrapper.orderByDesc(Course::getId);
        Page<Course> page = courseService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    //修改数据，文件分享
    @PostMapping("/update/{fileNameList}")
    public Result update(@PathVariable String fileNameList, HttpServletRequest request) {
        //获取token，当Redis中的key
        String token = request.getHeader("token");
        int userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
        //拆分数据信息
        String substring = fileNameList.substring(0, fileNameList.length() - 1);
        //取消分享，分享
        String isShare = fileNameList.substring(fileNameList.length() - 1);

        ArrayList<String> fileList = ListUtil.toList(substring.split(","));
        LambdaUpdateWrapper<Course> share = null;
        for (String fileName : fileList) {
            share = new LambdaUpdateWrapper<Course>()
                    .eq(Course::getFileName, fileName).eq(Course::getFileUserId, userId)
                    .set(Course::getIsShare, isShare);
            courseService.update(share);
        }

        return Result.success();
    }

    //修改描述
    @PutMapping("/update/description/{fileName}/{fileDescription}")
    public Result updateDescription(@PathVariable String fileName, @PathVariable String fileDescription, HttpServletRequest request) {
        //获取token，当Redis中的key
        String token = request.getHeader("token");
        int userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));

        LambdaUpdateWrapper<Course> set = new LambdaUpdateWrapper<Course>()
                .eq(Course::getFileName, fileName).eq(Course::getFileUserId, userId)
                .set(Course::getFileDescription, fileDescription);
        courseService.update(set);
        return Result.success();
    }

    /*
    取消分享
     */
    @GetMapping("/noShare/{fileName}")
    public Result noShare(@PathVariable String fileName, HttpServletRequest request) {
        //获取token，当Redis中的key
        String token = request.getHeader("token");
        int userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));

        LambdaUpdateWrapper<Course> set = new LambdaUpdateWrapper<Course>()
                .eq(Course::getFileName, fileName).eq(Course::getFileUserId, userId)
                .set(Course::getIsShare, "0");
        courseService.update(set);
        return Result.success();
    }

    /*
    热度排序
     */
    @GetMapping("/heat")
    public Result hotSort() {
        Map<Integer, List<CourseUser>> group = SimpleQuery.group(new LambdaQueryWrapper<CourseUser>(), CourseUser::getCourseId);
        Map<Integer, Long> map =new HashMap<>();
        group.forEach((k, v) -> {
            long count = v.size();
            map.put(k,count);
        });
        List<Course> list = new  ArrayList<>();
//        courseService.list().stream().sorted(Comparator.comparing());


        return Result.success();
    }
}

